package com.hongshan.wallet.core.trading

import android.app.Application
import android.databinding.ObservableField
import android.view.View
import com.hongshan.wallet.Constant
import com.hongshan.wallet.base.MyViewModel
import com.hongshan.wallet.bean.OrderDescBean
import com.hongshan.wallet.format
import com.hongshan.wallet.log
import com.hongshan.wallet.router.RouterIndex
import com.hongshan.wallet.router.go
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * Copyright Zhangxx.
 * Copyright (c) 2019
 * All rights reserved
 *
 * @project  : Wallet
 * @package  : com.example.wallet.core.trading
 * @author   : zhangxx
 * @date     : 2019/3/26
 * @email    : qq957413212@hotmail.com
 * @desc     : //TUDO
 */
class TradingRecycleViewModel(application: Application) : MyViewModel(application) {

    val money = ObservableField<String>()
    val status = ObservableField<String>()
    //    val statusColor = ObservableField<Int>()
    val receiveType = ObservableField<String>()
    val time = ObservableField<String>()

    var job: Job? = null

    var orderId:Int? = null

    var refresh:(()->Unit)? = null

    val desc = View.OnClickListener {
        go(RouterIndex.ORDER_DESC, mapOf(Constant.ROUTE_PARAMS_KEY.ORDER_ID to orderId))
    }

    fun setOrderDescBean(orderDesc: OrderDescBean) {
        money.set(orderDesc.investor_price)
        status.set(
            when (orderDesc.sub_status) {
                0 -> "未支付"
                1 -> "交易完成"
                2 -> "异常完成"
                3 -> "补单完成"
                4 -> "异常关闭"
                5 -> "交易超时"
                else -> null
            }
        )
        startDown(orderDesc)
        receiveType.set(orderDesc.pay_method_name)
        orderId = orderDesc.id
        time.set(orderDesc.create_time.format("yyyy-MM-dd HH:mm"))
    }

    fun startDown(orderDesc: OrderDescBean) {
        if (orderDesc.sub_status == 0) {
            val time = orderDesc.expire_time - System.currentTimeMillis() / 1000
            job = GlobalScope.launch(Dispatchers.Main) {
                if (time > 0) {
                    for (i in time downTo 0) {
                        status.set(i.format("mm分ss秒"))
                        delay(1000)
                    }
                    status.set("已过期")
                    log("time end")
                    refresh?.invoke()

                }
            }
        }
    }

    fun stopDown(){
        job?.cancel()
    }

}